const courseDao = require('../dao/courseDao');

class CourseServices {
  // 获取课程分类
  async getCategories() {
    try {
      return await courseDao.getAllCategories();
    } catch (error) {
      throw new Error(`获取课程分类失败: ${error.message}`);
    }
  }

  // 获取推荐课程
  async getRecommendedCourses(limit = 10) {
    try {
      return await courseDao.getRecommendedCourses(limit);
    } catch (error) {
      throw new Error(`获取推荐课程失败: ${error.message}`);
    }
  }

  // 搜索课程
  async searchCourses(keyword, page = 1, limit = 10) {
    try {
      if (!keyword || keyword.trim() === '') {
        throw new Error('搜索关键词不能为空');
      }
      return await courseDao.searchCourses(keyword.trim(), page, limit);
    } catch (error) {
      throw new Error(`搜索课程失败: ${error.message}`);
    }
  }

  // 获取课程列表
  async getCourseList(filters = {}, page = 1, limit = 10) {
    try {
      return await courseDao.getCourseList(page, limit, filters);
    } catch (error) {
      throw new Error(`获取课程列表失败: ${error.message}`);
    }
  }

  // 获取课程详情
  async getCourseDetail(courseId) {
    try {
      const course = await courseDao.findById(courseId);
      if (!course) {
        throw new Error('课程不存在');
      }

      // 增加观看次数
      await courseDao.incrementViewCount(courseId);

      return course;
    } catch (error) {
      throw new Error(`获取课程详情失败: ${error.message}`);
    }
  }

  // 创建课程
  async createCourse(courseData) {
    try {
      // 验证分类是否存在
      if (courseData.category_id) {
        const category = await courseDao.findCategoryById(courseData.category_id);
        if (!category) {
          throw new Error('课程分类不存在');
        }
      }

      return await courseDao.createCourse(courseData);
    } catch (error) {
      throw new Error(`创建课程失败: ${error.message}`);
    }
  }

  // 更新课程
  async updateCourse(courseId, updateData) {
    try {
      // 验证课程是否存在
      const existingCourse = await courseDao.findById(courseId);
      if (!existingCourse) {
        throw new Error('课程不存在');
      }

      // 验证分类是否存在
      if (updateData.category_id) {
        const category = await courseDao.findCategoryById(updateData.category_id);
        if (!category) {
          throw new Error('课程分类不存在');
        }
      }

      return await courseDao.updateCourse(courseId, updateData);
    } catch (error) {
      throw new Error(`更新课程失败: ${error.message}`);
    }
  }

  // 删除课程
  async deleteCourse(courseId) {
    try {
      const course = await courseDao.findById(courseId);
      if (!course) {
        throw new Error('课程不存在');
      }

      return await courseDao.deleteCourse(courseId);
    } catch (error) {
      throw new Error(`删除课程失败: ${error.message}`);
    }
  }

  // 点赞课程
  async likeCourse(courseId) {
    try {
      const course = await courseDao.findById(courseId);
      if (!course) {
        throw new Error('课程不存在');
      }

      await courseDao.incrementLikeCount(courseId);
      return true;
    } catch (error) {
      throw new Error(`点赞课程失败: ${error.message}`);
    }
  }

  // 报名课程
  async enrollCourse(courseId, userId) {
    try {
      const course = await courseDao.findById(courseId);
      if (!course) {
        throw new Error('课程不存在');
      }

      if (course.status !== 'published') {
        throw new Error('课程未发布，无法报名');
      }

      // 这里可以添加报名记录到数据库的逻辑
      // 暂时只增加报名人数
      await courseDao.incrementEnrollmentCount(courseId);

      return true;
    } catch (error) {
      throw new Error(`报名课程失败: ${error.message}`);
    }
  }

  // 创建课程分类
  async createCategory(categoryData) {
    try {
      return await courseDao.createCategory(categoryData);
    } catch (error) {
      throw new Error(`创建分类失败: ${error.message}`);
    }
  }

  // 更新课程分类
  async updateCategory(categoryId, updateData) {
    try {
      const category = await courseDao.findCategoryById(categoryId);
      if (!category) {
        throw new Error('分类不存在');
      }

      return await courseDao.updateCategory(categoryId, updateData);
    } catch (error) {
      throw new Error(`更新分类失败: ${error.message}`);
    }
  }

  // 删除课程分类
  async deleteCategory(categoryId) {
    try {
      const category = await courseDao.findCategoryById(categoryId);
      if (!category) {
        throw new Error('分类不存在');
      }

      return await courseDao.deleteCategory(categoryId);
    } catch (error) {
      throw new Error(`删除分类失败: ${error.message}`);
    }
  }

  // 获取热门课程
  async getPopularCourses(limit = 10) {
    try {
      const filters = { status: 'published' };
      const result = await courseDao.getCourseList(1, limit, filters);
      
      // 按观看次数和点赞数排序
      result.list.sort((a, b) => {
        const scoreA = a.view_count * 0.7 + a.like_count * 0.3;
        const scoreB = b.view_count * 0.7 + b.like_count * 0.3;
        return scoreB - scoreA;
      });

      return result.list;
    } catch (error) {
      throw new Error(`获取热门课程失败: ${error.message}`);
    }
  }

  // 获取免费课程
  async getFreeCourses(page = 1, limit = 10) {
    try {
      const filters = { 
        status: 'published',
        is_free: true 
      };
      return await courseDao.getCourseList(page, limit, filters);
    } catch (error) {
      throw new Error(`获取免费课程失败: ${error.message}`);
    }
  }

  // 根据难度获取课程
  async getCoursesByDifficulty(difficulty, page = 1, limit = 10) {
    try {
      const filters = { 
        status: 'published',
        difficulty 
      };
      return await courseDao.getCourseList(page, limit, filters);
    } catch (error) {
      throw new Error(`获取课程失败: ${error.message}`);
    }
  }

  // 根据分类获取课程
  async getCoursesByCategory(categoryId, page = 1, limit = 10) {
    try {
      // 验证分类是否存在
      const category = await courseDao.findCategoryById(categoryId);
      if (!category) {
        throw new Error('分类不存在');
      }

      const filters = { 
        status: 'published',
        category_id: categoryId 
      };
      return await courseDao.getCourseList(page, limit, filters);
    } catch (error) {
      throw new Error(`获取分类课程失败: ${error.message}`);
    }
  }
}

module.exports = new CourseServices();
